package com.itcast.springboot.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itcast.springboot.waste_recovery.domain.UserAddress;
import com.itcast.springboot.waste_recovery.mapper.UserAddressMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author 郭泽鹏
 * @Date 2020/8/24 9:54
 * @Version 1.0
 * @Description 地址工具类
 */
@Component
public class AddressUtil {
    @Resource
    UserAddressMapper userAddressMapper;

    /**
     * 设置默认地址
     * @param userId 用户id
     * @param addressId 地址id
     * @return 是否成功
     */
    public Integer setAddressDefault(Integer userId, Integer addressId){
        QueryWrapper<UserAddress> userAddressWrapper = new QueryWrapper();
        //状态
        Integer result = -1;
        //将原来的默认地址设置为false
        userAddressWrapper.eq("address_user_id", userId)
                .eq("address_is_default", true);
        List<UserAddress> userAddresses = userAddressMapper.selectList(userAddressWrapper);
        for (UserAddress userAddress : userAddresses) {
            userAddress.setAddressIsDefault(false);
            result = userAddressMapper.updateById(userAddress);
        }
        UserAddress userAddress = null;
        if (result >= 0){
            //设置新的默认地址
            userAddress = userAddressMapper.selectById(addressId);
            userAddress.setAddressIsDefault(true);
            result = userAddressMapper.updateById(userAddress);
        }
        return result;
    }
}
